package com.kinon.ceshiaccount.fragment.home;

import android.content.ContentValues;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.ceshiaccount.R;
import com.kinon.ceshiaccount.adapter.OrderAdapter;
import com.kinon.ceshiaccount.adapter.urgent.U_OrderAdapter;
import com.kinon.ceshiaccount.application.AccountApplication;
import com.kinon.ceshiaccount.bean.DataOrderBean;
import com.kinon.ceshiaccount.bean.DetailsBean;
import com.kinon.ceshiaccount.bean.base.OrdersBean;
import com.kinon.ceshiaccount.bean.urgent.U_OrderBean;
import com.kinon.ceshiaccount.constant.Constant;
import com.kinon.ceshiaccount.fragment.BaseFragment;
import com.kinon.ceshiaccount.network.HttpManage;
import com.kinon.ceshiaccount.network.StrCallback;
import com.kinon.ceshiaccount.sunmi.bean.TableBean;
import com.kinon.ceshiaccount.sunmi.print.AidlUtil;
import com.kinon.ceshiaccount.util.SPManage;
import com.kinon.ceshiaccount.view.CusOrderDialog;
import com.kinon.ceshiaccount.view.CustomDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.LinkedList;

import retrofit2.Call;
import retrofit2.Response;

import static org.litepal.crud.DataSupport.where;

/**
 * Created by luohao on 2017-06-16.
 * 订单界面，负责打印订餐小票，以及通知订餐的人员
 */

public class OrderFragment extends BaseFragment
        implements View.OnClickListener, OrderAdapter.OnPrintClickListener {
    /**
     * 每页显示的个数
     */
    private final int page = 50;
    /**
     * 获得订单的类型
     */
    private final String GET_ORDER_TYPE = "0";
    private View mView;
    /**
     * 未打印的人数
     */
    private TextView tv_noPrint;
    /**
     * 一键通知
     */
    private TextView tv_keyNotice;
    /**
     * 上下拉刷新
     */
    private SmartRefreshLayout smart_order;
    /**
     * 订单的listview
     */
    private ListView list_order;
    /**
     * 订单集合
     */
    private ArrayList<OrdersBean> orderlist;
    /**
     * 订单适配器
     */
    private OrderAdapter adapter;
    /**
     * 显示的页数下标
     */
    private int offset = 0;
    private Context context;

    /**
     * 紧急情况下的处理数据
     */
    private ArrayList<U_OrderBean> uOlist = null;
    private U_OrderAdapter urgentAdapter = null;
    private int noPrintNum = 0;
    private U_OrderAdapter.OnPrintClickListener onPrint = new
            U_OrderAdapter.OnPrintClickListener() {
                @Override
                public void onItemClick(int position) {
                    if (uOlist != null) {
                        seleteTakeTime(position);
                    }
                }
            };
    private AdapterView.OnItemClickListener itemClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            CusOrderDialog dialog = new CusOrderDialog
                    (getActivity(), orderlist.get(i));
            dialog.show();


        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_order_layout, container, false);
        return mView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        context = AccountApplication.getInstance();
        tv_noPrint = (TextView) mView.findViewById(R.id.tv_noPrint);
        tv_keyNotice = (TextView) mView.findViewById(R.id.tv_keyNotice);
        smart_order = (SmartRefreshLayout) mView.findViewById(R.id.smart_order);
        list_order = (ListView) mView.findViewById(R.id.list_order);

        orderlist = new ArrayList<>();
        tv_keyNotice.setOnClickListener(this);
        //上下拉刷新
        setSmartRefreshLayout();

        urgentSet();


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            urgentSet();
        } else {

        }
    }

    public void urgentSet() {
        if (!Constant.URGENT_TYPE) {
            list_order.setOnItemClickListener(itemClick);
            orderlist.clear();
            adapter = new OrderAdapter(getContext(), orderlist);
            list_order.setAdapter(adapter);
            adapter.setprintClickListener(this);
            //获得订单信息
            getOrderInfo();
        } else {
            getUOrder();
        }
    }

    /**
     * 紧急情况下运行的代码
     */
    private void getUOrder() {
        uOlist =
                (ArrayList<U_OrderBean>) DataSupport.findAll(U_OrderBean.class, true);
        noPrintNum = where("print=?", "0").count(U_OrderBean.class);
        tv_noPrint.setText("未打印人数:" + noPrintNum);

        urgentAdapter = new U_OrderAdapter(getContext(), uOlist);
        list_order.setAdapter(urgentAdapter);
        urgentAdapter.setprintClickListener(onPrint);
    }

    private void seleteTakeTime(int position) {
        ContentValues values = new ContentValues();
        values.put("print", 1);
        DataSupport.updateAll(U_OrderBean.class, values, "dayno=?",
                uOlist.get(position).getDayno());
        uOlist.get(position).setPrint(1);
        urgentAdapter.notifyDataSetChanged();
        noPrintNum--;
        tv_noPrint.setText("未打印人数:" + noPrintNum);
    }

    @Override
    public void onItemClick(int position) {
        tv_noPrint.setText("未打印人数:" + position);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_noPrint:
                dialogKeyPrint();
                break;
            case R.id.tv_keyNotice:
                noticeDialog();
                break;
        }
    }

    private void dialogKeyPrint() {
        CustomDialog dialog = new CustomDialog(getContext(), null,
                "一键打印存在打印不完全的风险是否一键打印", null, null,
                new CustomDialog.DialogClickListener() {
                    @Override
                    public void onDialogClick(int btn) {
                        if (btn == 1) {
                            for (int i = 0; i < orderlist.size(); i++)
                                print(i);
                        }
                    }

                });
        dialog.show();
    }

    private void print(int position) {
        LinkedList<TableBean> tabelist = new LinkedList<>();
        String[] text;

        for (DetailsBean i : orderlist.get(position).getDetails()) {
            text = new String[]{i.getName(), "*" + i.getAmount(), "¥" + i.getPrice()};
            tabelist.add(new TableBean(text));
        }
        AidlUtil.getInstance().myPrint(tabelist,
                orderlist.get(position).getTotalamount(),
                orderlist.get(position).getTotal(),
                orderlist.get(position).getOrderno(),
                orderlist.get(position).getBook_time(),
                orderlist.get(position).getName(),
                orderlist.get(position).getUsername(),
                orderlist.get(position).getDayno()
        );
    }

    /**
     * 上下拉刷新监听
     */
    private void setSmartRefreshLayout() {
        smart_order.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                smart_order.finishRefresh(2 * 1000);
                if (!Constant.URGENT_TYPE) {
                    orderlist.clear();
                    offset = 0;
                    getOrderInfo();
                }


            }
        });
        smart_order.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                smart_order.finishLoadmore(2 * 1000);
                if (!Constant.URGENT_TYPE) {
                    offset += page;
                    getOrderInfo();
                }
            }
        });

    }

    /**
     * 得到后台的订单列表
     */
    private void getOrderInfo() {
        Call<String> call = HttpManage.getRequestApi().getOrders
                (SPManage.getInstance().getToken(), page + "", offset + "", GET_ORDER_TYPE);
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String base) {
                Gson gson = new Gson();
                DataOrderBean order = gson.fromJson(base, DataOrderBean.class);
                orderlist.addAll(order.getOrders());
                adapter.notifyDataSetChanged();
                tv_noPrint.setText("未打印人数:" + order.getUnprintnum());
            }

            @Override
            public void onError(int code, String error) {
                Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void noticeDialog() {
        CustomDialog dialog = new CustomDialog(getContext(),
                "是否通知所有用户?",
                new CustomDialog.DialogClickListener() {
                    @Override
                    public void onDialogClick(int btn) {
                        if (btn == 1) {
                            keyNotice();
                        }
                    }
                });
        dialog.show();
    }

    /**
     * 一键通知
     */
    private void keyNotice() {
        Call<String> call = HttpManage.getRequestApi().noticeAllUsers
                (SPManage.getInstance().getToken());
        call.enqueue(new StrCallback<String>() {
            @Override
            public void onSuccess(Response<String> response, String base) {
                try {
                    JSONObject object = new JSONObject(response.body());
                    Toast.makeText(context, object.getString("msg"),
                            Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(int code, String error) {
                Toast.makeText(context, error, Toast.LENGTH_SHORT).show();
            }
        });
    }

}
